package com.dianrui.agent.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dianrui.agent.Constant;
import com.dianrui.agent.R;
import com.dianrui.agent.adapter.MessageNewListAdapter;
import com.dianrui.agent.bean.MsgList;
import com.dianrui.agent.event.MsgListRfresh;
import com.dianrui.agent.event.RfreshMy;
import com.dianrui.agent.okhttp.OkHttpRequest;
import com.dianrui.agent.util.SharedUtil;
import com.dianrui.agent.util.StringUtils;
import com.dianrui.agent.util.ToastUtil;
import com.dianrui.agent.util.Url;
import com.dianrui.agent.view.SwipeMenuLayout;
import com.google.gson.JsonObject;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MessageNewActivity extends BaseActivity {

    private List<MsgList> msgLists=new ArrayList<>();
    private int pageIndex=1;
    private MessageNewListAdapter adapter;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;


    public int getContentViewId() {
        return R.layout.message_new_list;
    }

    @Override
    public void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        title.setText("我的消息");
        LinearLayoutManager layoutManager = new LinearLayoutManager(MessageNewActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MessageNewListAdapter(R.layout.item_message, msgLists,MessageNewActivity.this);
        recyclerView.setAdapter(adapter);
        getMsgList(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getMsgList( true);
                refreshLayout.finishRefresh();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageIndex++;
                getMsgList(false);
                refreshLayout.finishLoadMore();
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MsgList messageModel = msgLists.get(position);
                switch (view.getId()){
                    case R.id.click_message:
                        SwipeMenuLayout layout= (SwipeMenuLayout) view.getParent();
                        TextView title=layout.findViewById(R.id.title);
                        TextView time=layout.findViewById(R.id.time);
                        TextView content=layout.findViewById(R.id.contents);
                        TextView msg_show_red_dot=layout.findViewById(R.id.show_msg_reddot);
                        ImageView msg_img=layout.findViewById(R.id.msg_img);

                        if (!layout.isExpand) {
                            Intent intent=new Intent(MessageNewActivity.this, MessageDetails.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("id", messageModel.messages_id);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }else {
                            layout.smoothClose();
                        }
                        break;

                    case R.id.delete:
                            DelMsg(messageModel.messages_id,position);
                        break;

                    default:
                        break;
                }


            }
        });
        adapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.click_message:
                        SwipeMenuLayout layout= (SwipeMenuLayout) view.getParent();
                        layout.smoothExpand();
                        break;
                }
                return true;
            }
        });





    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MsgListRfresh msgListRfresh) {
        getMsgList(true);
    }

    private void getMsgList(final boolean isRfresh) {
        if (isRfresh) {
            pageIndex=1;
        }
        JsonObject msgListJson=new JsonObject();
        msgListJson.addProperty("p",pageIndex);
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl()+Url.MSG_LIST, msgListJson.toString(),  new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (isRfresh) {
                    msgLists.clear();
                }
                if (!StringUtils.isEmpty(result)&&!isFinishing()) {
                    try {
                        JSONObject jsonObject=new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            JSONArray data=jsonObject.optJSONArray("data");
                            if (data.length()>0) {
                                for (int i = 0; i <data.length() ; i++) {
                                    MsgList msgList=new MsgList();
                                    msgList.messages_id=data.optJSONObject(i).optString("messages_id");
                                    msgList.title=data.optJSONObject(i).optString("title");
                                    msgList.contents=data.optJSONObject(i).optString("contents");
                                    msgList.create_time=data.optJSONObject(i).optString("create_time");
                                    msgList.is_read=data.optJSONObject(i).optString("is_read");
                                    msgList.send_time=data.optJSONObject(i).optString("send_time");
                                    msgLists.add(msgList);
                                }
                                adapter.setNewData(msgLists);
                                refreshLayout.finishLoadMore();
                            }
                        }else if ("1001".equals(jsonObject.optString("status"))){
                            refreshLayout.finishLoadMore();
                            ToastUtil.showToast(jsonObject.optString("message"));
                        }else if ("1002".equals(jsonObject.optString("status"))) {
                            refreshLayout.finishLoadMore();
                            spUtils.clear();
                            ToastUtil.showToast(jsonObject.optString("message"));
                            JumpActivitys(LoginActivity.class);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (msgLists.size()<=0) {
                    adapter.getData().clear();
                    adapter.setEmptyView(LayoutInflater.from(MessageNewActivity.this).inflate(R.layout.empty_view, null));
                    adapter.notifyDataSetChanged();
                }else {
                    recyclerView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }





    private void DelMsg(String msg_id,int postion) {
        JsonObject msgListJson=new JsonObject();
        msgListJson.addProperty("admin_id",spUtils.getString("admin_id"));
        msgListJson.addProperty("messages_id",msg_id);
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl()+ Url.DELMESSAGE, msgListJson.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject=new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            EventBus.getDefault().post(new RfreshMy());
                            ToastUtil.showToast(jsonObject.optString("message"));
                        }else if ("1001".equals(jsonObject.optString("status"))){
                            ToastUtil.showToast(jsonObject.optString("message"));
                        }else if ("1002".equals(jsonObject.optString("status")))  {
                            ToastUtil.showToast(jsonObject.optString("message"));
                            spUtils.clear();
                            JumpActivitys(LoginActivity.class);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    @OnClick(R.id.back)
    public void onViewClicked() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
